package com.three.DAO;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseDAO {
    Connection con=null;
    PreparedStatement ps=null;
    ResultSet rs=null;
    int count;

    public static Connection getConn(){
        Connection conn=null;
        try{
            Properties p=new Properties();
            p.load(new FileInputStream("jdbc.properties"));
            Class.forName(p.getProperty("classname"));
            String url=p.getProperty("url");
            String username=p.getProperty("username");
            String password=p.getProperty("password");
            conn= DriverManager.getConnection(url,username,password);
        }catch (IOException e){
            e.printStackTrace();
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }catch (SQLException e){
            e.printStackTrace();
        }
        return conn;
    }

    public ResultSet exeQuery(String sql, Object[] values){
        con=getConn();
        try {
            ps=con.prepareStatement(sql);
            for(int i=0;i<values.length;i++){
                ps.setObject(i+1,values[i]);
            }
            rs=ps.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }

    public int exeUpdate(String sql, Object[] values){
        con=getConn();
        try {
            ps=con.prepareStatement(sql);
            for(int i=0;i<values.length;i++){
                ps.setObject(i+1,values[i]);
            }
            count=ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }

    public void closeAll(){
        try{
            if(rs!=null){
                rs.close();
            }
            if(ps!=null){
                ps.close();
            }
            if(con!=null){
                con.close();
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
    }
}
